package com.dts.server.common.base;

import java.io.File;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import com.dts.server.common.enums.ResultCode;
import com.dts.server.common.exception.CustomException;
import com.dts.server.common.result.HttpResult;

/**
 * @ClassName:  BaseController
 * @author 范旭蛟
 * @date 2021年10月8日 下午9:07:00
 * @Description: controller基础类
 */
public class BaseController {
    
    
    @Value("${upload.rootPath}")
    private String rootPath;
    
    /**
     * 默认成功返回
     *
     * @param data
     * @return
     */
    protected <T> HttpResult<T> responseOK() {
        return HttpResult.ok(null);
    }
    
	/**
	 * 默认成功返回
	 *
	 * @param data
	 * @return
	 */
	protected <T> HttpResult<T> responseOK(T data) {
		return HttpResult.ok(data);
	}

	/**
	 * 默认成功返回带消息
	 *
	 * @param data
	 * @param msg
	 * @return
	 */
	protected <T> HttpResult<T> responseOK(T data, String msg) {
		return HttpResult.ok(data, msg);
	}

	/**
	 * 默认失败返回, 带信息
	 *
	 * @param message
	 * @return
	 */
	protected <T> HttpResult<T> responseFail(String message) {
	    return responseFail(ResultCode.S_UNKNOWN_ERROR, message);
	}

	/**
	 * 默认失败返回，带code
	 *
	 * @param code
	 * @return
	 */
	protected <T> HttpResult<T> responseFail(ResultCode code) {
	    return responseFail(code, code.getMessage());
	}

	/**
	 * 失败返回 
	 *
	 * @param code    错误Code
	 * @param message 若为null，则使用Code对应的默认信息
	 * @return
	 */
	/**
	 * @param code
	 * @param message
	 * @return
	 */
	/**
	 * @param code
	 * @param message
	 * @return
	 */
	protected <T> HttpResult<T> responseFail(ResultCode code, String message) {
	    HttpResult<T> restResult = new HttpResult<>();
	    restResult.setCode(code.getCode());
	    message = message == null ? code.getMessage() : message;
	    restResult.setMessage(message);
	    return restResult;
	}
	
	/**
	 * 上传文件
	 * @param image
	 * @param basePath
	 * @return
	 */
	protected String uploadFile(MultipartFile file, String basePath) throws Exception{
	    if(file ==null || file.isEmpty()){
	        throw new CustomException(ResultCode.PARAM_FILE_EMPTY);
	    }
	    String fileName = file.getOriginalFilename();
	    String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        String realFileName = uuid+suffixName;
        //保存到本地
        File dest = new File(rootPath+basePath+realFileName);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        file.transferTo(dest);
        return basePath+realFileName;
	}
}
